# Alexander F. Gazmararian
# afg2@princeton.edu

# Load packages
library(tidyverse)
library(modelsummary)
# Load data
g <- readRDS("data/NatRegQual_Winter21.rds")
# Make income ordered
g$income5 <- gsub("[$]", "", g$income5)
g$income5 <- factor(g$income5, ordered = TRUE, levels = c("Less than 29,999", "30,000 - 59,999", "60,000 - 99,999", "100,000 or more", "Prefer not to say"))
# Create function to create summary statistics
get_summary <- function(dat, file) {
  require(modelsummary)
  require(tidyverse)
  datasummary(
    formula = (Age = age) + Female  + Hispanic + Black + (College = CollegeDegree) + (`Fossil Fuel Employment` = ffemploy) + 
      (`Full-Time Employed` = employfull) + (Democrat = Dem) + (Republican = Rep) + (Liberal = Lib) + (Conservative = Con) +
      (`Climate Change Concern` = GlobalWarm_bin) + (Income = income5) ~ Mean + SD + N + Percent(),
    data = dat,
    fmt = 2,
    escape = FALSE,
    output = "latex"
  ) %>%
    cat(., file = file)
  # Trim table shell
  tbl <- readLines(file, warn = FALSE)
  tbl <- tbl[-c(1,2,26)]
  cat(tbl, file = file)
}
# Summary statistics for national sample
get_summary(subset(g, sample %in% c("credibility", "Roosevelt")), file = "tables/tbl_summarystat_nationaldec21feb22.txt")
# Gulf Coast Sample
get_summary(subset(g, region == "gulf_coast"), file = "tables/tbl_summarystat_gulfcoast.txt")
# Industrial Midwest
get_summary(subset(g, region == "industrial_heartland"), file = "tables/tbl_summarystat_midwest.txt")
# New Mexico
get_summary(subset(g, region == "new_mexico"), file = "tables/tbl_summarystat_newmex.txt")
# SWPA and surrounding
get_summary(subset(g, region == "pennsylvania"), file = "tables/tbl_summarystat_swpa.txt")
